<!--
  * app小程序用户
  *
  * @Author:    M
  * @Date:      2024-10-18 20:45:10
  * @Copyright  Transmute实验室
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">
      <a-form-item label="用户名" class="smart-query-form-item">
        <a-input style="width: 150px" v-model:value="queryForm.userName" placeholder="用户名" />
      </a-form-item>
      <a-form-item label="昵称" class="smart-query-form-item">
        <a-input style="width: 150px" v-model:value="queryForm.nickName" placeholder="昵称" />
      </a-form-item>
      <a-form-item label="手机号码" class="smart-query-form-item">
        <a-input style="width: 150px" v-model:value="queryForm.phone" placeholder="手机号码" />
      </a-form-item>
      <a-form-item class="smart-query-form-item">
        <a-button type="primary" @click="queryData">
          <template #icon>
            <SearchOutlined />
          </template>
          查询
        </a-button>
        <a-button @click="resetQuery" class="smart-margin-left10">
          <template #icon>
            <ReloadOutlined />
          </template>
          重置
        </a-button>
      </a-form-item>
    </a-row>
  </a-form>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="false">
    <!---------- 表格操作行 begin ----------->
    <div class="btn-group">
      <a-button class="btn" @click="showForm" type="primary">添加用户</a-button>
      <a-button class="btn" @click="confirmBatchDelete" :disabled="selectedRowKeyList.length == 0">批量删除</a-button>
      <a-radio-group class="btn" v-model:value="queryForm.disabledFlag" style="flex-shrink: 0" @change="queryData">
        <a-radio-button :value="undefined">全部</a-radio-button>
        <a-radio-button :value="false">启用</a-radio-button>
        <a-radio-button :value="true">禁用</a-radio-button>
      </a-radio-group>
      <span class="smart-table-column-operate">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.APP.USER" :refresh="queryData" />
      </span>
    </div>
    <!---------- 表格操作行 end ----------->

    <!---------- 表格 begin ----------->
    <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="userId" bordered :loading="tableLoading"
      :pagination="false" :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }">
      <template #bodyCell="{ text, record, column }">
        <template v-if="column.dataIndex === 'disabledFlag'">
          <a-tag :color="text ? 'error' : 'processing'">{{ text ? '禁用' : '启用' }}</a-tag>
        </template>
        <template v-else-if="column.dataIndex === 'gender'">
          <span>{{ $smartEnumPlugin.getDescByValue('GENDER_ENUM', text) }}</span>
        </template>
        <template v-if="column.dataIndex === 'action'">
          <div class="smart-table-operate">
            <a-button @click="showForm(record)" type="link">编辑</a-button>
            <a-button @click="onResetPassword(record.userId)" type="link">重置密码</a-button>
            <a-button @click="onDelete(record)" danger type="link">删除</a-button>
          </div>
        </template>
      </template>
    </a-table>
    <!---------- 表格 end ----------->

    <div class="smart-query-table-page">
      <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :defaultPageSize="queryForm.pageSize" v-model:current="queryForm.pageNum" v-model:pageSize="queryForm.pageSize"
        :total="total" @change="queryData" @showSizeChange="queryData" :show-total="(total) => `共${total}条`" />
    </div>

    <UserForm ref="formRef" @reloadList="queryData" />

  </a-card>
</template>
<script setup>
import { reactive, ref, onMounted } from 'vue';
import _ from 'lodash';
import { message, Modal } from 'ant-design-vue';
import { userApi } from '/@/api/app/user/user-api';
import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
import { smartSentry } from '/@/lib/smart-sentry';
import TableOperator from '/@/components/support/table-operator/index.vue';
import UserForm from './components/user-form.vue';
import { TABLE_ID_CONST } from '/@/constants/support/table-id-const';

// ---------------------------- 表格列 ----------------------------

const columns = ref([
  {
    title: '用户ID',
    dataIndex: 'userId',
    ellipsis: true,
    width: 70,
  },
  {
    title: '用户名',
    dataIndex: 'userName',
    ellipsis: true,
  },
  {
    title: '昵称',
    dataIndex: 'nickName',
    ellipsis: true,
  },
  {
    title: '手机号',
    dataIndex: 'phone',
    ellipsis: true,
    width: 100,
  },
  {
    title: '性别',
    dataIndex: 'gender',
    ellipsis: true,
    width: 50,
  },
  {
    title: '企业',
    dataIndex: 'enterpriseName',
    ellipsis: true,
    width: 200,
  },
  {
    title: '状态',
    dataIndex: 'disabledFlag',
    ellipsis: true,
    width: 65,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    ellipsis: true,
    width: 150,
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    ellipsis: true,
    width: 150,
  },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    width: 260,
  },
]);

// ---------------------------- 查询数据表单和方法 ----------------------------

const queryFormState = {
  userName: undefined, //用户名
  nickName: undefined, //昵称
  phone: undefined, //手机号码
  disabledFlag: undefined,
  pageNum: 1,
  pageSize: 10,
};
// 查询表单form
const queryForm = reactive({ ...queryFormState });
// 表格加载loading
const tableLoading = ref(false);
// 表格数据
const tableData = ref([]);
// 总数
const total = ref(0);

// 重置查询条件
function resetQuery() {
  let pageSize = queryForm.pageSize;
  Object.assign(queryForm, queryFormState);
  queryForm.pageSize = pageSize;
  queryData();
}

// 查询数据
async function queryData() {
  tableLoading.value = true;
  try {
    let queryResult = await userApi.queryPage(queryForm);
    tableData.value = queryResult.data.list;
    total.value = queryResult.data.total;
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    tableLoading.value = false;
  }
}


onMounted(queryData);

// ---------------------------- 添加/修改 ----------------------------
const formRef = ref();

function showForm(data) {
  let params = {};
  if (data) {
    params = _.cloneDeep(data);
    params.disabledFlag = params.disabledFlag ? 1 : 0;
  }
  formRef.value.show(params);
}

// ---------------------------- 重置密码 ----------------------------
function onResetPassword(userId) {
  Modal.confirm({
    title: '提示（重置后密码为：123456）',
    content: '确定要重置密码吗?',
    okText: '重置',
    onOk() {
      return requestResetPassword(userId);
    },
    cancelText: '取消',
    onCancel() { },
  });
}

async function requestResetPassword(userId) {
  try {
    await userApi.resetPassword(userId);
    message.success('重置密码成功');
    queryData();
  } catch (e) {
    smartSentry.captureError(e);
  }
}

// ---------------------------- 单个删除 ----------------------------
//确认删除
function onDelete(data) {
  Modal.confirm({
    title: '提示',
    content: '确定要删除选吗?',
    okText: '删除',
    okType: 'danger',
    onOk() {
      return requestDelete(data);
    },
    cancelText: '取消',
    onCancel() { },
  });
}

//请求删除
async function requestDelete(data) {
  try {
    await userApi.delete(data.userId);
    message.success('删除成功');
    queryData();
  } catch (e) {
    smartSentry.captureError(e);
  }
}

// ---------------------------- 批量删除 ----------------------------

// 选择表格行
const selectedRowKeyList = ref([]);

function onSelectChange(selectedRowKeys) {
  selectedRowKeyList.value = selectedRowKeys;
}

// 批量删除
function confirmBatchDelete() {
  Modal.confirm({
    title: '提示',
    content: '确定要批量删除这些数据吗?',
    okText: '删除',
    okType: 'danger',
    onOk() {
      return requestBatchDelete();
    },
    cancelText: '取消',
    onCancel() { },
  });
}

//请求批量删除
async function requestBatchDelete() {
  try {
    await userApi.batchDelete(selectedRowKeyList.value);
    message.success('删除成功');
    queryData();
  } catch (e) {
    smartSentry.captureError(e);
  }
}
</script>
<style scoped lang="less">
.btn-group {
  margin: 10px 0;

  .btn {
    margin-right: 8px;
  }
}
</style>